from django.http import JsonResponse
from blueking.component.shortcuts import get_client_by_request


def get_bizs_list(request):
    '''
    获取业务列表
    api文档https://apigw.ce.bktencent.com/docs/component-api/default/CC/search_business/doc
    '''
    # 从环境配置获取APP信息，从request获取当前用户信息
    client = get_client_by_request(request)
    kwargs = {
        "fields": ["bk_biz_id", "bk_biz_name"],
        "page": {
            "start": 0,
            "limit": 10,
            "sort": ""
        }
    }
    # client.组件名称.API名称
    response = client.cc.search_business(kwargs)
    return JsonResponse(response)

def get_sets_list(request):
    '''
    根据业务id，查询业务下的集群列表
    api文档
    https://apigw.ce.bktencent.com/docs/component-api/default/CC/search_set/doc
    '''
    client = get_client_by_request(request)
    kwargs = {
        "bk_biz_id": request.GET.get('bk_biz_id'),
        "fields": [
            "bk_set_id",
            "bk_set_name",
            "bk_biz_id",
            "bk_created_at",
            "bk_supplier_account"
        ]
    }
    response = client.cc.search_set(kwargs)
    return JsonResponse(response)

def get_modules_list(request):
    '''
    根据业务id，查询业务下的模块列表
    '''
    client = get_client_by_request(request)
    kwargs = {
        "bk_biz_id": request.GET.get('bk_biz_id'),
        "bk_set_id": request.GET.get("bk_set_id"),
        "fields": ["bk_module_id", "bk_module_name", "bk_set_id", "bk_biz_id", "bk_created_at", "bk_supplier_account"]
    }
    response = client.cc.search_module(kwargs)
    return JsonResponse(response)

def get_hosts_list(request):
    client = get_client_by_request(request)
    kwargs = {
        "bk_biz_id": request.GET.get('bk_biz_id'),
        "page": {"start": 0, "limit": 100, },
        "fields": ["bk_host_id", "bk_cloud_id", "bk_host_innerip", "bk_os_type", "bk_mac", "operator",
                   "bk_bak_operator"]
    }
    if request.GET.get("bk_set_id"):
        kwargs["bk_set_ids"] = [int(request.GET.get("bk_set_id"))]
    if request.GET.get("bk_module_id"):
        kwargs["bk_module_ids"] = [int(request.GET.get("bk_module_id"))]
    rules = []
    if request.GET.get("operator"):
        rules.append({
            "field": "operator",
            "operator": "equal",
            "value": request.GET.get("operator")

        })
    if rules:
        kwargs["host_property_filter"] = {
            "condition": "AND",
            "rules": rules
        }
    response = client.cc.list_biz_hosts(kwargs)
    return JsonResponse(response)


def get_host_detail(request):
    client = get_client_by_request(request)
    kwargs = {
        "bk_host_id": request.GET.get('bk_host_id')
    }
    response = client.cc.get_host_base_info(kwargs)
    return JsonResponse(response)
